#include "common.h"
#include <pthread.h>

pthread_mutex_t text_mutex = PTHREAD_MUTEX_INITIALIZER;

bool SYSTEM_RUNNING_FALG = true;
bool SYSTEM_END_FALG = false; //主函数main结束
bool SYSTEM_SIG_EIXT_FALG = false;

void *sys_end_pth(void *arg)
{
    while (SYSTEM_END_FALG) {}
    reemoon_info ("====================> system resatrt <====================\n");

    // int ret = execl("/reemoon/ui_app", "ui_app", (char *)NULL);
    // if (ret == -1) {
    //     perror("execl");
    // }
    system("app &");
    exit (0);
}

void reemoon_system_restart(void)
{
    SYSTEM_RUNNING_FALG = false;
    // 重启程序
    pthread_t sys_end_id;
    pthread_create(&sys_end_id, NULL, sys_end_pth, NULL);
}

char * reemoon_get_system_time(char *time_buffer, uint8_t size) 
{
    time_t current_time;
    struct tm *time_info;
    // 获取从1970年1月1日00:00:00 UTC到当前时刻的秒数
    time(&current_time);
    // 将秒数转换为本地时间结构体
    time_info = localtime(&current_time);
    // 按照"年-月-日 时:分:秒"格式输出当前时间
    
    snprintf(time_buffer,size,"%04d-%02d-%02d %02d:%02d:%02d",
           time_info->tm_year + 1900,
           time_info->tm_mon + 1,
           time_info->tm_mday,
           time_info->tm_hour,
           time_info->tm_min,
           time_info->tm_sec
        );

    return time_buffer;
}

// 删除字符串值中的字母
int reemoon_del_en(const char * src, char *dest, int src_size, int dest_size)
{
    if (dest_size < src_size)
        return -1;
    size_t len = strlen(src);
    size_t j = 0;
    for (size_t i = 0; i < len; i++) {
        if (src[i] >= '0' && src[i] <= '9') {
            dest[j++] = src[i];
        }
    }
    dest[j] = '\0';
    return 0;
}

// 读取文件内容
int reemoon_read_file(const char *filename, char *buff, size_t size) 
{
    int fd = open(filename, O_RDONLY);
    if (fd == -1) {
        reemoon_error ("open file(%s) error\n", filename);
        return -1;
    }
    struct stat file_stat;
    if (fstat(fd, &file_stat) == -1) {
        perror("fstat error");
        close(fd);
        return -1;
    }
    if (size < file_stat.st_size+1) // 预留'/0'位置
    {
        printf ("file size: %ld, buffsize not less than: %ld", file_stat.st_size, file_stat.st_size+1);
        return -1;
    }
    ssize_t bytes_read = read(fd, buff, file_stat.st_size);
    if (bytes_read == -1) {
        perror("read file error");
        close(fd);
        return -1;
    }
    buff[bytes_read] = '\0';
    close(fd);
    return bytes_read;
}
// 写文件函数
int reemoon_write_file(const char *filename, const char *buff, size_t size)
{
    // 打开文件，使用 O_WRONLY 以只写模式打开，O_CREAT 若文件不存在则创建，O_TRUNC 若文件已存在则截断内容
    int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1) {

        reemoon_error ("open file(%s) error\n", filename);
        return -1;
    }

    // 写入数据到文件
    ssize_t bytes_written = write(fd, buff, size);
    if (bytes_written == -1) {
        reemoon_error("write file error");
        close(fd);
        return -1;
    }

    // 检查是否全部写入
    if ((size_t)bytes_written != size) {
        fprintf(stderr, "Only %zd bytes written out of %zu\n", bytes_written, size);
        close(fd);
        return -1;
    }

    // 关闭文件描述符
    close(fd);
    return bytes_written;
}

int reemoon_run_script(const char *script_path)
{
    // 要运行的脚本路径，这里假设脚本在当前目录下
    // 调用 system() 函数运行脚本
    int status = system(script_path);
    if (status == -1) {
        perror("Failed to execute the script");
        return EXIT_FAILURE;
    } else if (WIFEXITED(status)) {
        // 脚本正常退出，获取退出状态码
        int exit_status = WEXITSTATUS(status);
        if (exit_status == 0) {
            printf("Script executed successfully.\n");
        } else {
            printf("Script exited with status %d.\n", exit_status);
        }
    } else {
        printf("Script did not terminate normally.\n");
    }
}

// 定义不同级别的日志打印函数
#if REEMOON_ERROR
void reemoon_error_(const char *file, int line, const char *fmt,...) {
    va_list args;
    va_start(args, fmt);
    fprintf(stderr, "[ERROR] [file: %s:%d] ", file, line);
    vfprintf(stderr, fmt, args);
    va_end(args);
}
#endif

#if REEMOON_WARN
void reemoon_warn_(const char *file, int line, const char *fmt,...) {
    va_list args;
    va_start(args, fmt);
    fprintf(stderr, "[WARN] [file: %s:%d] ", file, line);
    vfprintf(stderr, fmt, args);
    va_end(args);
}
#endif

#if REEMOON_INFO
// 实现带有文件和行号参数的 reemoon_info_real 函数
void reemoon_info_(const char *file, int line, const char *fmt, ...) {
    va_list args;
    va_start(args, fmt);
    // 打印文件和行号信息
    fprintf(stdout, "[INFO] [file: %s:%d] ", file, line);
    // 打印格式化信息
    vfprintf(stdout, fmt, args);
    va_end(args);
}
#endif

#if REEMOON_IGNORE
void reemoon_ignore_(const char *file, int line, const char *fmt, ...) {
    va_list args;
    va_start (args, fmt);
    fprintf(stdout, "[IGNORE] [file: %s:%d] ", file, line);
    vfprintf (stdout, fmt, args);
    va_end (args);
}
#endif
